#!/usr/bin/ruby

# gnuplot commands
GP_CMDS = ["set term png", "set samples 1000", "set grid", \
        "set yrange[-0.01:1.01]", "set xtics #{60*30}"]
#GP_CMDS = ["set term dumb", "set grid", "set yrange[0:1]"]

require 'cgi'
require "sqlite3"
require 'pp'

def mk_plot_cmd(entries)
    return "plot " + entries.map { |a,b,y|
        "#{a}<x && x<#{b} ? #{y.to_f/(b-a)}"
    }.join(':') + ":0 notitle"
end

def plot(entries)
    xmin = entries.map {|e| e[0]}.min
    xmax = entries.map {|e| e[1]}.max

    xrange_cmd = "set xrange[#{xmin}:#{xmax}]"
    plot_cmd = mk_plot_cmd(entries)

    gp_cmd = (GP_CMDS + [xrange_cmd, plot_cmd] ).join('; ')
    
    puts gp_cmd

    puts "Content-type: image/png\n\n"
    #puts "Content-type: text/plain\n\n"
    $stdout.write(`echo \"#{gp_cmd}\" | gnuplot`)
end
